I'm creating a piano tiles game from javascript using canvas, I have a case where the user has to press a button in an exact location and time. I have to give the user a 100ms tolerance so if the user pressed the button 100ms earlier or later it still counts.
A solution would be appreciated.
The yellow and blue blocks are the tiles so the user has to press the keys at the exact time and location of the tiles
Usually, it is best not to mix representation with the underlying logic.
You need to represent the task (note to be played/button pressed) along with the time (or time offset when do you expect it. Then once the button is pressed compare if the current time matches the expected time.
here is a toy example that may give you ideas
var startTime = 0;
$(document).ready(function(){
$('#butt').on('click', function(){
var curTime = new Date().getTime();
if (startTime === 0)
{
startTime = new Date().getTime()
$('#log').val('Now try pressing it exactly every second')
}
else
{
$('#log').val('You were off by ' + (curTime - startTime - 1000)+'ms');
startTime = curTime
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="butt">
Press me once a second
</button>
<textarea id='log' rows=10 cols=50>Click button to start</textarea>